<template>
  <div class="product-category-page">
    <div class="page-header">
      <h2 class="page-title">产品分类</h2>
      <el-button type="text" class="return-btn" @click="handleReturn">返回</el-button>
    </div>

    <div class="action-area">
      <el-button 
        type="primary" 
        class="add-btn" 
        @click="openAddDialog"
        style="background-color: #00b4b4; border-color: #00b4b4;"
      >
        增加
      </el-button>
    </div>

    <el-table 
      :data="categoryList" 
      border 
      style="width: 100%;"
      :row-key="row => row.id"
    >
      <el-table-column prop="index" label="序号" sortable width="80" />
      <el-table-column prop="name" label="分类名称" sortable />
      <el-table-column prop="brand" label="归属品牌" sortable />
      <el-table-column label="是否隐藏" width="120">
        <template #default="scope">
          <el-switch 
            v-model="scope.row.isHidden" 
            :active-value="true" 
            :inactive-value="false" 
        
            active-color="#00b4b4" 
            @change="handleHiddenChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button 
            type="warning" 
         
            @click="openEditDialog(scope.row)"
            style="background-color: #f5a623; border-color: #f5a623;"
          >
            修改
          </el-button>
          <el-button 
            type="danger" 
           
            @click="handleDelete(scope.row)"
            style="background-color: #f56c6c; border-color: #f56c6c;"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-area">
      <span class="total-info">共 {{ categoryList.length }} 条 共 {{ totalPages }} 页</span>
      <el-pagination
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="prev, pager, next"
        :total="categoryList.length"
      />
      <el-select 
        v-model="pageSize" 
        @change="handleSizeChange" 
        placeholder="条数/页" 
        style="width: 100px; margin-left: 10px;"
      >
        <el-option label="10条/页" value="10" />
        <el-option label="20条/页" value="20" />
        <el-option label="30条/页" value="30" />
      </el-select>
      <span>跳至</span>
      <el-input 
        v-model="jumpPage" 
        type="number" 
        style="width: 50px; margin: 0 5px;"
        @keyup.enter="handleJump"
        :min="1"
        :max="totalPages"
      />页
      <el-button 
        type="primary" 
       
        style="background-color: #00b4b4; border-color: #00b4b4;"
        @click="handleJump"
      >
        确定
      </el-button>
    </div>

    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑产品分类' : '新增产品分类'" 
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="formRef" 
        :model="form" 
        label-width="100px"
        :rules="formRules"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="归属品牌" prop="brand">
          <el-select v-model="form.brand" placeholder="请选择归属品牌">
            <el-option label="品牌A" value="品牌A" />
            <el-option label="品牌B" value="品牌B" />
            <el-option label="品牌C" value="品牌C" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否隐藏">
          <el-switch 
            v-model="form.isHidden" 
            :active-value="true" 
            :inactive-value="false" 
    
            active-color="#00b4b4" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="submitForm"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue';
import { ElMessage, ElMessageBox, ElEmpty } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();

const categoryList = ref([
  {
    id: '1',
    index: 1,
    name: '21世纪',
    brand: '品牌A',
    isHidden: false
  }
]);

const form = reactive({
  id: '',
  name: '',
  brand: '品牌A',
  isHidden: false
});

const formRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 50, message: '分类名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  brand: [
    { required: true, message: '请选择归属品牌', trigger: 'change' }
  ]
};

const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref(null);

const currentPage = ref(1);
const pageSize = ref(10);
const jumpPage = ref('');
const totalPages = computed(() => {
  return Math.ceil(categoryList.value.length / pageSize.value) || 1;
});

const openAddDialog = () => {
  isEdit.value = false;
  Object.assign(form, {
    id: '',
    name: '',
    brand: '品牌A',
    isHidden: false
  });
  
  nextTick(() => {
    if (formRef.value) {
      formRef.value.resetFields();
    }
  });
  dialogVisible.value = true;
};

const openEditDialog = (row) => {
  isEdit.value = true;
  Object.assign(form, JSON.parse(JSON.stringify(row)));
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate();
    }
  });
  dialogVisible.value = true;
};

const submitForm = async () => {
  try {
    await formRef.value.validate();
    
    if (isEdit.value) {
      const index = categoryList.value.findIndex(item => item.id === form.id);
      if (index !== -1) {
        categoryList.value.splice(index, 1, { ...form });
        ElMessage.success('编辑成功');
      }
    } else {
      const newIndex = categoryList.value.length + 1;
      const newCategory = {
        ...form,
        id: Date.now().toString(),
        index: newIndex
      };
      categoryList.value.unshift(newCategory);
      ElMessage.success('新增成功');
    }
    
    dialogVisible.value = false;
  } catch (error) {
    if (error.name !== 'ValidationError') {
      ElMessage.error('操作失败，请重试');
      console.error(error);
    }
  }
};

const handleHiddenChange = async (row) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 300));
    ElMessage.success(`是否隐藏状态已更新为${row.isHidden ? 'ON' : 'OFF'}`);
  } catch (error) {
    row.isHidden = !row.isHidden;
    ElMessage.error('状态更新失败');
    console.error(error);
  }
};

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定删除该产品分类吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const index = categoryList.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      categoryList.value.splice(index, 1);
      categoryList.value.forEach((item, i) => {
        item.index = i + 1;
      });
      ElMessage.success('删除成功');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
      console.error(error);
    }
  }
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  jumpPage.value = val;
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  jumpPage.value = 1;
};

const handleJump = () => {
  if (!jumpPage.value) return;
  
  let page = Number(jumpPage.value);
  if (isNaN(page) || page < 1) {
    page = 1;
  } else if (page > totalPages.value) {
    page = totalPages.value;
  }
  
  currentPage.value = page;
  jumpPage.value = page;
};

const handleReturn = () => {
  router.back();
};

watch(totalPages, (newVal) => {
  if (currentPage.value > newVal && newVal > 0) {
    currentPage.value = newVal;
    jumpPage.value = newVal;
  }
});
</script>

<style scoped>
.product-category-page {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.return-btn {
  color: #666;
}

.action-area {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 20px;
  flex-wrap: wrap;
}

.total-info {
  color: #666;
}

.el-pagination {
  margin: 0;
}

.el-input {
  width: auto;
}
</style>